<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="title"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      class="dialog-form"
    >
      <el-descriptions :column="1" border class="custom-descriptions">
        <!-- 工程类表单 (requirementType = 0) -->
        <template v-if="requirementType === 1">
          <el-descriptions-item label="*合同名称">
            <el-form-item prop="contractId">
              <div style="display: flex; align-items: left;">
                <el-select
                  style="width: 250px;"
                  v-model="form.contractId"
                  placeholder="符合需求类别的合同"
                  clearable
                >
                  <el-option
                    v-for="item in engineeringContracts"
                    :key="item.id"
                    :label="item.cname"
                    :value="item.id"
                  />
                </el-select>
                <el-link
                  v-if="engineeringContracts.length === 0 || !engineeringContracts"
                  style="margin-left: 5px;"
                  @click="handleCreateContractClick"
                  size="small"
                >无符合要求合同，点击前往新建</el-link>
              </div>
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="需求名称">
            <el-input
              v-model="form.dname"
              disabled
              style="width: 100%;"
            />
          </el-descriptions-item>
          
          <el-descriptions-item label="需求类别">
            <el-input
              v-model="requirementTypeLabel"
              disabled
              style="width: 100%;"
            />
          </el-descriptions-item>
        </template>
        
        <!-- 直销类表单 (requirementType = 1) -->
        <template v-else-if="requirementType === 2">
          <el-descriptions-item label="*合同名称">
            <el-form-item prop="contractId">
              <el-input
                v-model="form.contractId"
                placeholder="支持1~128个字符"
                :maxlength="128"
                show-word-limit
                style="width: 100%;"
              />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="合同类型">
            <el-input
              v-model="contractTypeLabel"
              disabled
              style="width: 100%;"
            />
          </el-descriptions-item>
          
          <el-descriptions-item label="关联需求">
            <el-input
              v-model="form.dname"
              disabled
              style="width: 100%;"
            />
          </el-descriptions-item>
          
          <el-descriptions-item label="需求编号">
            <el-input
              v-model="form.dno"
              disabled
              style="width: 100%;"
            />
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import {
  getContractPage
} from '@/api/business/contract'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    default: '关联合同'
  },
  requirementType: {
    type: Number,
    required: true,
  },
  requirementData: {
    type: Object,
    default: () => ({})
  }
})

// 定义emits
const emit = defineEmits(['close', 'submit', 'update:visible'])

// 表单引用
const formRef = ref(null)
// 工程类合同
const engineeringContracts = ref([])

// 表单数据
const form = reactive({
  contractId: '',
  dname: props.requirementData.dname || '',
  dno: props.requirementData.dno || '',
  id: props.requirementData.id || ''
})

// 监听requirementData的变化，确保表单数据实时更新
watch(() => props.requirementData, (newData) => {
  if (newData) {
    form.dname = newData.dname || ''
    form.dno = newData.dno || ''
    form.id = newData.id || ''
  }
}, { immediate: true, deep: true })

// 计算属性 - 获取需求类型标签
const requirementTypeLabel = computed(() => {
  return props.requirementType === 1 ? '工程类' : '直销类'
})

const handleCreateContractClick = () => {
  // console.log('handleCreateContractClick');
  router.push({ path: '/business/contract' })
}

// 计算属性 - 获取合同类型标签
const contractTypeLabel = computed(() => {
  return props.requirementType === 1 ? '工程类' : '直销类'
})

// 表单校验规则
const rules = {
  contractId: [
    { required: true, message: '请输入合同名称', trigger: 'blur' },
    { min: 1, max: 128, message: '合同名称长度在 1 到 128 个字符', trigger: 'blur' }
  ]
}
const getContractList = () => { 
  const params = { pageNum: 1, pageSize: 10000 }
  getContractPage(params).then(res => {
    if (res.code === 200) {
      const arr = res?.data?.list || []
      engineeringContracts.value = arr.filter(item => item.ctype === 1)
    }
  })
}
onMounted(() => {
  // console.log('requirementData', props.requirementData);
  getContractList()
})

// 处理关闭
const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.contractId = ''
  emit('update:visible', false)
  emit('close')
}

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    emit('submit', { ...form })
    emit('update:visible', false)
  } catch (error) {
    console.log('表单验证失败', error)
  }
}
</script>

<style scoped>
/* 从createModal.vue迁移相关样式 */
.custom-descriptions {
  width: 100%;
}
.custom-descriptions .el-form-item {
  margin-bottom: 0;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #EBEEF5;
}

.custom-descriptions .el-descriptions__label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: center;
  padding: 18px 10px 0 10px !important;
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: transparent !important;
}
</style>